package com.yzcrm.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.aliyuncs.utils.StringUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log;
import com.yzcrm.common.config.exception.YzcrmException;
import com.yzcrm.utils.R;

public class ExceptionInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation invocation) {

        try {
            invocation.invoke();
        } catch (Exception e) {

            String message = formatException(e);

            invocation.getController().renderJson(R.error(message));

            Log.getLog(invocation.getController().getClass()).error("响应错误", e);

        } finally {

        }

    }

    /**
     * 格式化异常信息，用于友好响应用户
     * @param e
     * @return
     */
    private static String formatException(Exception e){

        String message = null;
        Throwable ourCause = e;
        while ((ourCause = e.getCause()) != null) {
            e = (Exception) ourCause;
        }
        String eClassName = e.getClass().getName();
        // 一些常见异常提示
        if("java.lang.NumberFormatException".equals(eClassName)) {
            message = "请输入正确的数字";
        } else if("java.lang.NullPointerException".equals(eClassName)){
            message = "未知bug，请联系管理员";
        } else if (e instanceof YzcrmException || e instanceof RuntimeException) {
            message = e.getMessage();
            if(ObjectUtil.isNull(message)) {
                message = e.toString();
            }
        }

        // 获取默认异常提示
        if (ObjectUtil.isNull(message)){
            message = "系统繁忙,请稍后再试";
        }

        // 替换特殊字符
        message = message.replaceAll("\"", "'");
        return message;
    }

}
